package com.aabte.auth.account.resource.facade;

import com.aabte.auth.account.application.AccountService;
import com.aabte.auth.account.domain.model.Account;
import com.aabte.auth.account.domain.model.AccountId;
import com.aabte.auth.account.domain.model.AccountName;
import com.aabte.auth.account.domain.model.Password;
import com.aabte.auth.account.resource.api.account.AccountDTO;
import com.aabte.auth.account.resource.facade.assembler.AccountDTOAssembler;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class AccountServiceFacade {

    @Resource
    private AccountService accountService;

    public AccountId register(String accountName, String accountPassword) {
        return accountService.createNewAccount(new AccountName(accountName), new Password(accountPassword));
    }

    public void updatePassword(String accountName, String currentPassword, String newPassword) {
        accountService.updatePassword(
                new AccountName(accountName),
                new Password(currentPassword),
                new Password(newPassword));
    }

    public Page<AccountDTO> accounts(Integer pageNumber, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNumber - 1, pageSize);
        Page<Account> accountPage = accountService.accounts(pageable);
        return toDTO(accountPage);
    }

    private Page<AccountDTO> toDTO(Page<Account> accountPage) {
        AccountDTOAssembler assembler = new AccountDTOAssembler();

        List<AccountDTO> content = new ArrayList<>(accountPage.getNumberOfElements());
        for (Account account : accountPage.getContent()) {
            content.add(assembler.toDTO(account));
        }

        return new PageImpl<>(
                content, accountPage.getPageable(), accountPage.getTotalElements());
    }
}
